import axios from 'axios';

import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import {getToken,removeToken,removeUserInfo} from '../utils/storageUtils';

const userAxios = axios.create({
    baseURL:"http://localhost:8888",
    // baseURL:'/api',
    timeout:10000 //超时时间  10s
})

//请求拦截器
userAxios.interceptors.request.use(config=>{

    //1. 进度条
    NProgress.start();

    let token = getToken();

    console.log(token);
    //2. 设置请求头 - 将token携带到headers内部
    if(token){
        config.headers.token = token;
    }

    return config;
});

// 响应拦截器
userAxios.interceptors.response.use(res=>{
    //1. 进度条关闭
    NProgress.done();

    //2. 返回响应体数据
    return res.data;
},rea=>{
    //请求响应失败 - 执行到这里
    //1. 进度条关闭
    NProgress.done();

    //2. 判断响应状态码是否401 -> 需要身份验证
    if(rea.response.status===401){
        removeToken();

        removeUserInfo();

        alert('token非法或无效');

        window.location.href = '/login.html';
    }

    //向下传递错误
    throw rea;
})


export default userAxios;



